package br.com.gkarian.mydesk.intercepts;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.validator.ValidationException;
import br.com.gkarian.mydesk.anotacoes.AlteracaoIndevida;
import br.com.gkarian.mydesk.controller.MainController;
import br.com.gkarian.mydesk.web.UsuarioWeb;

@RequestScoped
@Intercepts
public class AlteracaoIndevidaInterceptor implements Interceptor {

	private static final Logger LOG = Logger.getLogger(AlteracaoIndevidaInterceptor.class);
	
	private final UsuarioWeb usuarioWeb;
	private final Result result;
	private final HttpServletRequest request;

	public AlteracaoIndevidaInterceptor(Result result, UsuarioWeb usuarioWeb,
			HttpServletRequest request) {
		this.usuarioWeb = usuarioWeb;
		this.result = result;
		this.request = request;
	}

	public boolean accepts(ResourceMethod method) {
		if (method.containsAnnotation(AlteracaoIndevida.class)) {
			String id = request.getParameter("usuario.id");
			String login = request.getParameter("usuario.login");
			if (usuarioWeb.isLogado()
					&& usuarioWeb.getLogado().getId().toString() != id
					&& !usuarioWeb.getLogado().getLogin().equals(login)) {
				LOG.info("***** Usuario: [" + usuarioWeb.toString()
						+ "] tentando alterar dados de usuario com ID [" + id + "]");
				return true;
			}
		}
		return false;
	}

	// eh executado quando accepts retornar True
	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object resourceInstance) throws InterceptionException, ValidationException {
		LOG.info("******************** Redirecionando para alteracaoIndevida");
		result.redirectTo(MainController.class).alteracaoIndevida();
	}
}